package org.zhangsh.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.zhangsh.socket.HostInfo;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-27
 */
public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    private int counter = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        System.out.println(HostInfo.THREAD_NAME + "request： ["+ msg + "] the counter : " + ++counter);

        String response = msg+DecoderUtil.DELIMITER;
        ByteBuf byteBuf = Unpooled.copiedBuffer(response.getBytes());
        System.out.println(HostInfo.THREAD_NAME + "response：" + response);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("end");
        super.channelReadComplete(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("remove");
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "异常" + cause.getMessage());
        ctx.close();
    }
}
